require('es6-promise').polyfill();

import axios from 'axios'


function errorAction(error) {
  return {
    type: 'ERROR_BILL_LINE',
    error
  }
}

function createBillLineData(data){
  return {
    type:'CREATE_BILL_LINE_DATA',
    data,
    date:Date.now()
  };
}

function loadBills(data) {
  return {
    type: 'LOAD_BILL_MANAGER_DATA',
    data
  }
}

export function apiMsgAction(msg) {
  return {
    type: 'API_MSG',
    msg
  }
}

function loadBillAsync(data) {
  if (typeof data.search_is_pay != 'undefined') {
    data.is_pay = data.search_is_pay
  }else {
    data.is_pay = null
  }
  return function(dispatch) {
    return axios.post('/api/bill/queryBillManager', data).then(
      resp => dispatch(loadBills(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function setBillLinesEmty() {
  return {
    type: 'EMTPY_BILL_DATA'
  }
}

export function createBillLineAsync(data) {
  return function(dispatch) {
    return axios.post('/api/billLine/create', data).then(
      resp => dispatch(createBillLineData(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

function editBillLineData(data){
  return {
    type:'EDIT_BILL_LINE_DATA',
    data,
    date:Date.now()
  };
}

export function editBillLineAsync(data) {
  return function(dispatch) {
    return axios.post('/api/billLine/update',data).then(
      resp => dispatch(loadBillAsync(data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function updatePayBillLineAsync(data) {
  data.is_pay = true
  console.log(data)
  return function(dispatch) {
    return axios.post('/api/billLine/updatePay',data).then(
      resp => dispatch(loadBillAsync(data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    )
  }
}

function deleteBillLineData(id) {
  return {
    type: 'DELETE_BILL_LINE_DATA',
    id
  };
}

export function deleteBillLineDataAsync(data){
  return function(dispatch) {
    return axios.get('/api/billLine/delete?id='+data.id).then(
      resp => dispatch(loadBillAsync(data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}
